package com.Policing.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;

/**
 * @类名 VibrateUtil
 * @TODO注释 //TODO 此工具类是用调用设备震动的工具类
 * @作者 蒋剑华
 * @创建日期 2023/10/11 13:49
 * @详情 略
 * @版本号 1.0.0
 **/
public class VibrateUtils {

    private static volatile VibrateUtils instance;
    private Vibrator vibrator;

    private VibrateUtils(Context context) {
        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    }

    public static VibrateUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (VibrateUtil.class) {
                if (instance == null) {
                    instance = new VibrateUtils(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    /**
     * 震动设备
     *
     * @param duration 震动持续时间（毫秒）
     */
    @SuppressLint("MissingPermission")
    public void vibrate(long duration) {
        if (vibrator == null || !vibrator.hasVibrator()) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0及以上版本
            vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            // Android 7.1及以下版本
            vibrator.vibrate(duration);
        }
    }

    /**
     * 停止震动
     */
    @SuppressLint("MissingPermission")
    public void cancel() {
        if (vibrator != null && vibrator.hasVibrator()) {
            vibrator.cancel();
        }
    }

}
